package org.jeecgframework.web.material.service.impl;

import org.activiti.engine.EngineServices;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.jeecgframework.web.activiti.dao.LeaveDao;
import org.jeecgframework.web.activiti.entity.Leave;
import org.jeecgframework.web.activiti.util.Variable;
import org.jeecgframework.web.material.service.OrderFormServiceI;
import org.jeecgframework.web.material.service.OrderProcessServiceI;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.CommonService;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.web.material.dao.OrderProcessDao;
<<<<<<< HEAD
=======
import org.jeecgframework.web.material.entity.FlowDetailIncomeEntity;
import org.jeecgframework.web.material.entity.FlowEntity;
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
import org.jeecgframework.web.material.entity.OrderInfoEntity;
import org.jeecgframework.web.material.entity.OrderInstallEntity;
import org.jeecgframework.web.material.entity.OrderMeasureEntity;
import org.jeecgframework.web.material.entity.OrderProcessEntity;
import org.jeecgframework.web.material.entity.OrderFormEntity;
import org.jeecgframework.web.material.entity.OrderProductEntity;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;

import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

@Service("orderProcessService")
@Transactional
public class OrderProcessServiceImpl extends CommonServiceImpl implements
		OrderProcessServiceI {
	@Autowired
	private IdentityService identityService;
   
<<<<<<< HEAD
	private Map<String,String> processActivity = new HashMap<String,String>();
	 
=======
	Map<String,String> processActivity = new HashMap<String,String>();
	 
	public Map<String, String> getProcessActivity() {
		initOrderActivity();
		return processActivity;
	}

	public void setProcessActivity(Map<String, String> processActivity) {
		this.processActivity = processActivity;
	}
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private ProcessEngine processEngine;

	@Autowired
	private OrderProcessDao processDao;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private OrderFormServiceI orderFormService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private CommonService commonService;
	

	private Logger logger = LoggerFactory.getLogger(getClass());

	public <T> void delete(T entity) {
		super.delete(entity);
		// 执行删除操作配置的sql增强
		this.doDelSql((OrderProcessEntity) entity);
	}

	public void addMain(OrderProcessEntity orderProcess,
			List<OrderFormEntity> orderFormList) {
		// 保存主信息
		this.save(orderProcess);

		/** 保存-xdkj */
		for (OrderFormEntity orderForm : orderFormList) {
			// 外键设置
			orderForm.setOrderProcessId(orderProcess.getId().toString());
			this.save(orderForm);
		}
		// 执行新增操作配置的sql增强
		this.doAddSql(orderProcess);
	}

	/**
	 * 启动订单流程
	 * 
	 * @param OrderProcessEntity
	 */
	public void processWorkFlowStart(OrderProcessEntity entity) {
		OrderProcessEntity order = processDao.getOrderProcess(2);
		order.setAssignedId(entity.getAssignedId());
		order.setAssignedName(entity.getAssignedName());
		order.setAssignedTel(entity.getAssignedTel());

		String businessKey = order.getId().toString();
		ProcessInstance processInstance = null;
		try {
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(order.getAssignedId());

			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("newOrderUser", order.getAssignedId());
			processInstance = runtimeService.startProcessInstanceByKey("order",
					businessKey, variables);
			String processInstanceId = processInstance.getId();
			//
			variables.put("measureUser", order.getAssignedId() + ","
					+ "4028808d4f96154c014f9635d5c90002");
			List<Task> tasks = processEngine.getTaskService().createTaskQuery()
					.taskAssignee(order.getAssignedId()).list();
			for (Task t : tasks) {

				if (processInstanceId.equals(t.getProcessInstanceId())) {
					processEngine.getTaskService().addCandidateUser(t.getId(),
							order.getAssignedId());
					processEngine.getTaskService().addCandidateUser(t.getId(),
							"4028808d4f96154c014f9635d5c90002");
					processEngine.getTaskService().complete(t.getId(),
							variables);
				}
			}
			order.setInstanceId(processInstanceId);
			// processInstan
			// processEngine.getTaskService().createTaskQuery().
			logger.debug(
					"start process of {key={}, bkey={}, pid={}, variables={}}",
					new Object[] { "leave", businessKey, processInstanceId,
							variables });
		} finally {
			identityService.setAuthenticatedUserId(null);
			this.save(order);
			logger.debug("save entity: {}", order);
		}

	}

	/**
	 * 启动订单流程
	 * 
	 * @param OrderProcessEntity
	 */
	public void processWorkFlowStart(List<OrderProductEntity> orderProductList) {
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
		for (OrderProductEntity orderProduct : orderProductList) {
			if (!oConvertUtils.isEmpty(orderProduct.getId())) {
				// 外键设置
				OrderProcessEntity process = new OrderProcessEntity();
				// 外键设置
				process.setOrderProductId(orderProduct);
				//
				/*
				process.setAssignedId(user.getId());
				process.setAssignedName(user.getUserName());
				process.setAssignedTel(user.getMobilePhone());*/
				this.save(process);
				String businessKey = process.getId().toString();
				ProcessInstance processInstance = null;
				try {
					// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
					identityService.setAuthenticatedUserId(process
							.getAssignedId());
					//启动流程
					Map<String, Object> variables = new HashMap<String, Object>();
					variables.put("newOrderUser", user.getId());
					processInstance = runtimeService.startProcessInstanceByKey(
							"order", businessKey, variables);
					String processInstanceId = processInstance.getId();
					//设置测量人员
					variables.put("measureUser", listMeasureUser(orderProduct
							.getOrderId().getId().toString()));
					ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
					//获取当前人员的待办任务
					List<Task> tasks = processEngine.getTaskService()
							.createTaskQuery()
							.taskAssignee(user.getId()).list();
					for (Task t : tasks) {
						if (processInstanceId.equals(t.getProcessInstanceId())) {
							//执行新订单流程
							processEngine.getTaskService().complete(t.getId(),
									variables);
							ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(t.getProcessInstanceId()).active().singleResult();
							process.setActivityId(instance.getActivityId());
							if(processActivity.size()<1){
								initOrderActivity();
							}
							process.setActivityName(processActivity.get(instance.getActivityId()));
						}
					}
					process.setInstanceId(processInstanceId);
					logger.debug(
							"start process of {key={}, bkey={}, pid={}, variables={}}",
							new Object[] { "leave", businessKey,
									processInstanceId, variables });
				} finally {
					identityService.setAuthenticatedUserId(null);
					//保存流程数据
					this.saveOrUpdate(process);
					logger.debug("save entity: {}", process);
				}

			}
		}
	}

	/**
	 * 获取安装人员.
	 */
	public List<String> listInstallerUser(String orderId) {

		List<String> users = new ArrayList<String>();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderInstallEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderInstallEntity> orderInstallEntityList = this.findHql(hql0,
				orderId);
		for (OrderInstallEntity entity : orderInstallEntityList) {
			users.add(entity.getEngineerId().getId().toString());
		}
		return users;
	}

	/**
	 * 测量人是否存在.
	 */
	public List<String> listMeasureUser(String orderId) {

		List<String> users = new ArrayList<String>();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderMeasureEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderMeasureEntity> orderMeasureEntityList = this.findHql(hql0,
				orderId);
		for (OrderMeasureEntity entity : orderMeasureEntityList) {
			users.add(entity.getEngineerId().getId().toString());
		}
		return users;
	}

	public void updateMain(OrderProcessEntity orderProcess,
			List<OrderFormEntity> orderFormList) {
		// 保存主表信息
		this.saveOrUpdate(orderProcess);
		// ===================================================================================
		// 获取参数
		Object id0 = orderProcess.getId();
		// ===================================================================================
		// 1.查询出数据库的明细数据-xdkj
		String hql0 = "from OrderFormEntity where 1 = 1 AND oRDER_PROCESS_ID = ? ";
		List<OrderFormEntity> orderFormOldList = this.findHql(hql0, id0);
		// 2.筛选更新明细数据-xdkj
		for (OrderFormEntity oldE : orderFormOldList) {
			boolean isUpdate = false;
			for (OrderFormEntity sendE : orderFormList) {
				// 需要更新的明细数据-xdkj
				if (oldE.getId().equals(sendE.getId())) {
					try {
						MyBeanUtils.copyBeanNotNull2Bean(sendE, oldE);
						this.saveOrUpdate(oldE);
					} catch (Exception e) {
						e.printStackTrace();
						throw new BusinessException(e.getMessage());
					}
					isUpdate = true;
					break;
				}
			}
			if (!isUpdate) {
				// 如果数据库存在的明细，前台没有传递过来则是删除-xdkj
				super.delete(oldE);
			}

		}
		// 3.持久化新增的数据-xdkj
		for (OrderFormEntity orderForm : orderFormList) {
			if (oConvertUtils.isEmpty(orderForm.getId())) {
				// 外键设置
				orderForm.setOrderProcessId(orderProcess.getId().toString());
				this.save(orderForm);
			}
		}
		// 执行更新操作配置的sql增强
		this.doUpdateSql(orderProcess);

	}

	public void delMain(OrderProcessEntity orderProcess) {
		// 删除主表信息
		this.delete(orderProcess);
		// ===================================================================================
		// 获取参数
		Object id0 = orderProcess.getId();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderFormEntity where 1 = 1 AND oRDER_PROCESS_ID = ? ";
		List<OrderFormEntity> orderFormOldList = this.findHql(hql0, id0);
		this.deleteAllEntitie(orderFormOldList);
	}

	/**
	 * 默认按钮-sql增强-新增操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doAddSql(OrderProcessEntity t) {
		return true;
	}

	/**
	 * 默认按钮-sql增强-更新操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doUpdateSql(OrderProcessEntity t) {
		return true;
	}

	/**
	 * 默认按钮-sql增强-删除操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doDelSql(OrderProcessEntity t) {
		return true;
	}

	/**
	 * 替换sql中的变量
	 * 
	 * @param sql
	 * @return
	 */
	public String replaceVal(String sql, OrderProcessEntity t) {
		sql = sql.replace("#{id}", String.valueOf(t.getId()));
		sql = sql.replace("#{order_product_id}",
				String.valueOf(t.getOrderProductId()));
		sql = sql.replace("#{activity_name}",
				String.valueOf(t.getActivityName()));
		sql = sql.replace("#{instance_id}", String.valueOf(t.getInstanceId()));
		sql = sql.replace("#{assigned_id}", String.valueOf(t.getAssignedId()));
		sql = sql.replace("#{assigned_name}",
				String.valueOf(t.getAssignedName()));
		sql = sql
				.replace("#{assigned_tel}", String.valueOf(t.getAssignedTel()));
		sql = sql.replace("#{is_merge}", String.valueOf(t.getIsMerge()));
		sql = sql.replace("#{parent_id}", String.valueOf(t.getParentId()));
		sql = sql.replace("#{remark}", String.valueOf(t.getRemark()));
		sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
		return sql;
	}

	@Transactional(readOnly = true)
	public OrderProcessEntity getOrderProcess(int id) {
		return processDao.getOrderProcess(id);
	}

<<<<<<< HEAD
	@Override
	public void completeTask(String taskId, Variable var, OrderFormEntity form) {
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
		// 流程
		Map<String, Object> variables = var.getVariableMap();
		
		variables.put("approval", Boolean.parseBoolean(form.getApproval()));
		variables.put("applyUserId", user.getId());
		variables.put("is_install", Boolean.parseBoolean(form.getIsInstall()));
		// 获取当前任务
		Task task = processEngine.getTaskService().createTaskQuery()
				.taskId(taskId).singleResult();

		// 获取流程ID
		String processInstanceId = task.getProcessInstanceId();
		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).active().singleResult();
		//获取当前待办人
		if("orderApproval".equals(processInstance.getActivityId())
		   ||"paymentDeadlineInstall".equals(processInstance.getActivityId())){
			OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
			OrderInfoEntity order = orderProcess.getOrderProductId().getOrderId();
			variables.put("applyUserId", order.getCreateManId());
		}
		//设置订单审核人员
		if("measure".equals(processInstance.getActivityId())){
			List<Map<String, Object>> roleUser =  this.commonService.findForJdbc(
					"select u.id from t_s_role r ,t_s_base_user u , t_s_role_user rel where rel.roleid=r.id and rel.userid=u.id and r.rolecode='approval'", null);
			List<String> userList= new ArrayList<String>();
			for(Map<String, Object> u:roleUser){
				userList.add(u.get("id").toString());
			}
			if(userList.size()>0){
				variables.put("approvalUser", userList);
			}else{
				variables.put("approvalUser", user.getId());
			}
		}
		
		// 保存当前表单
		String businessKey = processInstance.getBusinessKey();
		form.setOrderProcessId(businessKey);
		form.setOperateId(user.getId());
		form.setOperateName(user.getUserName());
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		form.setOperateTime(df.format(new Date()));
		form.setActivityId(processInstance.getActivityId());
		form.setActivityName(task.getName());
		
		// 执行用户任务
		if ("完成".equals(task.getName())) {
			orderFormService.save(form);
			if (Boolean.parseBoolean(form.getIsFinish())) {
				taskService.complete(taskId, variables);
			}
		} else if ("客户确认收货".equals(task.getName())) {
			if (Boolean.parseBoolean(form.getCustomerReceiving())) {
				orderFormService.save(form);
				taskService.complete(taskId, variables);
			}
		}else if("上门安装".equals(task.getName())){
			if (Boolean.parseBoolean(form.getIsFinish())) {
				orderFormService.save(form);
				taskService.complete(taskId, variables);
			}
		}else if("收尾款".equals(task.getName())){
			orderFormService.save(form);
			if (Boolean.parseBoolean(form.getIsFinish())) {
				taskService.complete(taskId, variables);
			}
		}else {
			orderFormService.save(form);
			taskService.complete(taskId, variables);
		}
		//安装完成后重新订单信息
		if("上门安装".equals(task.getName())&&Boolean.parseBoolean(form.getIsFinish())){
			OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
			OrderInfoEntity order = orderProcess.getOrderProductId().getOrderId();
			//更新订单信息
			order.setIsSubmit("2");
			this.saveOrUpdate(order);
		}
		// 安装人员安排
		if ("门市确认收货".equals(task.getName())
				&&Boolean.parseBoolean(form.getIsInstall())) {
			OrderProcessEntity order = getOrderProcess(Integer
					.parseInt(businessKey));
			List<String> userList = listInstallerUser(order.getOrderProductId()
					.getOrderId().getId().toString());
			// 发送通知
			if (userList.size() > 0) {
				runtimeService.setVariable(processInstanceId, "installUser",
						userList);
				runtimeService.signal(processInstanceId);
			}
		}
		// 执行自动归档
		if ("客户确认收货".equals(task.getName()) || "收尾款".equals(task.getName())) {
			processArchiving();
		}
		
		//更新流程信息
		OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
		
		orderProcess.setActivityName(processActivity.get(processInstance.getActivityId()));
		processInstance = runtimeService
				.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).active().singleResult();
		if(processInstance!=null
			&&!"measure".equals(processInstance.getActivityId())
			&&!"install".equals(processInstance.getActivityId())
			&&!"orderApproval".equals(processInstance.getActivityId())){
			//设置当前环节信息
			orderProcess.setActivityId(processInstance.getActivityId());
			if(processActivity.size()<1){
				initOrderActivity();
			}
			//设置待办人信息
			orderProcess.setAssignedId(user.getId());
			orderProcess.setAssignedName(user.getUserName());
			orderProcess.setAssignedTel(user.getMobilePhone());
		}
		//保存流程新流程信息
		this.saveOrUpdate(orderProcess);
		
	}
=======
	/**
	 * 单个流程环节执行
	 * @param taskId  任务编号
 	 * @param var  变量
	 * @param form 表单
	 */
	private void completeTaskSingle(String taskId, Variable var, OrderFormEntity form){
		// 当前用户
				TSUser user = ResourceUtil.getSessionUserName();
				// 流程
				Map<String, Object> variables = var.getVariableMap();
				
				variables.put("approval", Boolean.parseBoolean(form.getApproval()));
				variables.put("applyUserId", user.getId());
				variables.put("is_install", Boolean.parseBoolean(form.getIsInstall()));
				// 获取当前任务
				Task task = processEngine.getTaskService().createTaskQuery()
						.taskId(taskId).singleResult();

				// 获取流程ID
				String processInstanceId = task.getProcessInstanceId();
				ProcessInstance processInstance = runtimeService
						.createProcessInstanceQuery()
						.processInstanceId(processInstanceId).active().singleResult();
				//获取当前待办人
				if("orderApproval".equals(processInstance.getActivityId())
				   ||"install".equals(processInstance.getActivityId())){
					OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
					OrderInfoEntity order = orderProcess.getOrderProductId().getOrderId();
					variables.put("applyUserId", order.getCreateManId());
				}
				//设置订单审核人员
				if("measure".equals(processInstance.getActivityId())){
					List<Map<String, Object>> roleUser =  this.commonService.findForJdbc(
							"select u.id from t_s_role r ,t_s_base_user u , t_s_role_user rel where rel.roleid=r.id and rel.userid=u.id and r.rolecode='approval'", null);
					List<String> userList= new ArrayList<String>();
					for(Map<String, Object> u:roleUser){
						userList.add(u.get("id").toString());
					}
					if(userList.size()>0){
						variables.put("approvalUser", userList);
					}else{
						variables.put("approvalUser", user.getId());
					}
				}
				
				// 保存当前表单
				String businessKey = processInstance.getBusinessKey();
				form.setOrderProcessId(businessKey);
				form.setOperateId(user.getId());
				form.setOperateName(user.getUserName());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				form.setOperateTime(df.format(new Date()));
				form.setActivityId(processInstance.getActivityId());
				form.setActivityName(task.getName());
				
				// 执行用户任务
				if ("完成".equals(task.getName())) {
					orderFormService.save(form);
					if (Boolean.parseBoolean(form.getIsFinish())) {
						taskService.complete(taskId, variables);
					}
				} else if ("客户确认收货".equals(task.getName())) {
					if (Boolean.parseBoolean(form.getCustomerReceiving())) {
						orderFormService.save(form);
						taskService.complete(taskId, variables);
					}
				}else if("上门安装".equals(task.getName())){
					if (Boolean.parseBoolean(form.getIsFinish())) {
						orderFormService.save(form);
						taskService.complete(taskId, variables);
					}
				}else if("收尾款".equals(task.getName())){
					orderFormService.save(form);
					saveFlow(businessKey,form);
					if (Boolean.parseBoolean(form.getIsFinish())) {
						taskService.complete(taskId, variables);
					}
				}else {
					orderFormService.save(form);
					taskService.complete(taskId, variables);
				}
				//安装完成后重新订单信息
				if("上门安装".equals(task.getName())&&Boolean.parseBoolean(form.getIsFinish())){
					OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
					OrderInfoEntity order = orderProcess.getOrderProductId().getOrderId();
					//更新订单信息
					order.setIsSubmit("2");
					this.saveOrUpdate(order);
				}
				// 安装人员安排
				if ("门市确认收货".equals(task.getName())
						&&Boolean.parseBoolean(form.getIsInstall())) {
					OrderProcessEntity order = getOrderProcess(Integer
							.parseInt(businessKey));
					List<String> userList = listInstallerUser(order.getOrderProductId()
							.getOrderId().getId().toString());
					// 发送通知
					if (userList.size() > 0) {
						runtimeService.setVariable(processInstanceId, "installUser",
								userList);
						runtimeService.signal(processInstanceId);
					}
				}
				// 执行自动归档
				if ("客户确认收货".equals(task.getName()) || "收尾款".equals(task.getName())) {
					processArchiving();
				}
				
				//更新流程信息
				OrderProcessEntity orderProcess = getEntity(OrderProcessEntity.class, Integer.parseInt(processInstance.getBusinessKey()));
				
				processInstance = runtimeService
						.createProcessInstanceQuery()
						.processInstanceId(processInstanceId).active().singleResult();
				if(processInstance!=null){
					orderProcess.setActivityName(processActivity.get(processInstance.getActivityId()));
					if(!"measure".equals(processInstance.getActivityId())
							&&!"install".equals(processInstance.getActivityId())
							&&!"orderApproval".equals(processInstance.getActivityId())){
							//设置当前环节信息
							orderProcess.setActivityId(processInstance.getActivityId());
							if(processActivity.size()<1){
								initOrderActivity();
							}
							//设置待办人信息
							orderProcess.setAssignedId(user.getId());
							orderProcess.setAssignedName(user.getUserName());
							orderProcess.setAssignedTel(user.getMobilePhone());
						}
				}else{
					orderProcess.setActivityName("已归档");
					orderProcess.setAssignedId("");
					orderProcess.setAssignedName("");
					orderProcess.setAssignedTel("");
				}
				
				//保存流程新流程信息
				this.saveOrUpdate(orderProcess);
				
	}
	
	/**
	 * 保存财务.
	 */
	private void saveFlow(String keyId,OrderFormEntity form){
		List<OrderProcessEntity> processes = new ArrayList<OrderProcessEntity>();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderProcessEntity where 1 = 1 AND ID = ? ";
		TSUser user = ResourceUtil.getSessionUserName(); 
		processes= this.findHql(hql0,
				keyId);
		if(processes.size()>0){
			String hql1 = "from FlowEntity where 1 = 1 AND order_Id = ? ";
			List<FlowEntity> flow = this.findHql(hql1,
					processes.get(0).getOrderProductId().getOrderId().getId());
		    if(flow.size()>0){
		    	//保存收入信息
				FlowDetailIncomeEntity come= new FlowDetailIncomeEntity();
				come.setFlowId(flow.get(0));
				come.setMoney(Double.parseDouble(form.getPaymentDeadline()));
				come.setPayerId(user.getId());
				come.setPayerName(user.getUserName());
				come.setTradeTime(new Date());
				
				come.setCompanyId(user.getCompany());
				come.setReceiverId("0");
				come.setReceiverName(processes.get(0).getOrderProductId().getOrderId().getUserName());
				this.saveOrUpdate(come);
		    }
		}
	}
	
	/**
	 * 流程环节执行
	 * @param taskId  任务编号
 	 * @param var  变量
	 * @param form 表单
	 */
	@Override
	public void completeTask(String taskId, Variable var, OrderFormEntity form) {
		// 获取当前任务
		TaskService taskService = processEngine.getTaskService();
		Task oldetask = taskService.createTaskQuery()
						.taskId(taskId).singleResult();
		//执行父订单
		completeTaskSingle(taskId, var, form);
		
		
		if(oldetask!=null){
			String  instanceId = oldetask.getProcessInstanceId();
			ProcessInstance  instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).active().singleResult();
			if(instance!=null){
				//执行子订单
				String hql0 = "from OrderProcessEntity where 1 = 1 AND parent_id = ? ";
				List<OrderProcessEntity> orderProcessEntityList = this.findHql(hql0,
						instance.getBusinessKey());
				for (OrderProcessEntity entity : orderProcessEntityList) {
					Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(entity.getInstanceId()).active().singleResult();
					completeTaskSingle(task.getId(), var, form);
				}	
			}	
		}
   }
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61

	/**
	 * 流程归档.
	 */
	private void processArchiving() {
		List<Task> tasks = processEngine.getTaskService().createTaskQuery()
				.taskAssignee("archiving").list();
		for (Task t : tasks) {
			String processInstanceId = t.getProcessInstanceId();
			// 获取流程实例
			HistoryService historySvc = processEngine.getHistoryService();
			HistoricProcessInstance hisProcInst = historySvc
					.createHistoricProcessInstanceQuery()
					.processInstanceId(processInstanceId).singleResult();
			// 获取业务对象
			OrderProcessEntity process = getOrderProcess(Integer
					.parseInt(hisProcInst.getBusinessKey()));
			process.setActivityName("已归档");
			process.setAssignedId("");
			process.setAssignedName("");
			process.setAssignedTel("");
			// 保存业务数据
			this.saveOrUpdate(process);
			// 执行归档
			taskService.complete(t.getId());

		}
	}
	/**
	 * 初始化流程环节数据.
	 */
	private void initOrderActivity(){
<<<<<<< HEAD
		processActivity.put("newOrder", "新建订单");
		processActivity.put("measure", "尺寸测量");
		processActivity.put("orderApproval", "订单审核");
		processActivity.put("orderDown", "订单下发");
		processActivity.put("orderProduction", "生产");
		processActivity.put("orderFinish", "完成");
		processActivity.put("receiving", "门市确认收货");
		processActivity.put("install", "上门安装");
		processActivity.put("paymentDeadlineInstall", "收尾款");
		processActivity.put("paymentDeadlineNoinstall", "收尾款");
		processActivity.put("deliverGoods", "发货");
		processActivity.put("customerReceiving", "客户确认收货");
=======
		if(processActivity.size()<1){
			processActivity.put("newOrder", "新建订单");
			processActivity.put("measure", "尺寸测量");
			processActivity.put("orderApproval", "订单审核");
			processActivity.put("orderDown", "订单下发");
			processActivity.put("orderProduction", "生产");
			processActivity.put("orderFinish", "完成");
			processActivity.put("receiving", "门市确认收货");
			processActivity.put("install", "上门安装");
			processActivity.put("paymentDeadlineInstall", "收尾款");
			processActivity.put("paymentDeadlineNoinstall", "收尾款");
			processActivity.put("deliverGoods", "发货");
			processActivity.put("customerReceiving", "客户确认收货");
		}
	}

	/**
	 * 订单合并.
	 */
	@Override
	public void orderMerge(String ids, String parentId) {
		String[] idsStr = ids.split(",");
		for (String id:idsStr){
			if(!id.equals(parentId)){
				OrderProcessEntity order = this.getEntity(OrderProcessEntity.class, Integer.parseInt(id));
				if(order!=null){
					order.setIsMerge("true");
					order.setParentId(parentId);
				}
			}
			
		}
	}
	
	/**
	 * 订单拆分.
	 */
	@Override
	public void splitMerge(String ids) {
		String[] idsStr = ids.split(",");
		for (String id:idsStr){
			OrderProcessEntity order = this.getEntity(OrderProcessEntity.class, Integer.parseInt(id));
			if(order!=null){
				order.setIsMerge("");
				order.setParentId("");
			}
		}
	}

    /**
     * 任务签收.
     * @param taskId 任务ID
     */
	@Override
	public void claim(String taskId) {
		TaskService taskService = processEngine.getTaskService();
		// 获取当前任务
		Task oldetask = taskService.createTaskQuery()
				.taskId(taskId).singleResult();
		//父任务签收
		claimSignle(taskId);
		//子任务签收
		if(oldetask!=null){
			String  instanceId = oldetask.getProcessInstanceId();
			ProcessInstance  instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).active().singleResult();
			if(instance!=null){
				//执行子订单
				String hql0 = "from OrderProcessEntity where 1 = 1 AND parent_id = ? ";
				List<OrderProcessEntity> orderProcessEntityList = this.findHql(hql0,
						instance.getBusinessKey());
				for (OrderProcessEntity entity : orderProcessEntityList) {
					Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(entity.getInstanceId()).active().singleResult();
					claimSignle(task.getId());
				}
			}
				
		}
			
	}
	
	/**
	 * 单个任务签收.
	 * @param taskId 任务ID
	 */
	private void claimSignle(String taskId) {
		TSUser user = ResourceUtil.getSessionUserName();
		String userId = user.getId();

		TaskService taskService = processEngine.getTaskService();
		// 获取当前任务
		Task task = taskService.createTaskQuery()
				.taskId(taskId).singleResult();
		taskService.claim(taskId, userId);
		
        //签收后更新待办人信息
		ProcessInstance instance =runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).active().singleResult();
		
		if(instance!=null){
			OrderProcessEntity process = this.getEntity(OrderProcessEntity.class
					, Integer.parseInt(instance.getBusinessKey()));
			//设置待办人信息
			process.setAssignedId(user.getId());
			process.setAssignedName(user.getUserName());
			process.setAssignedTel(user.getMobilePhone());
			//保存待办人信息
			this.saveOrUpdate(process);
		}
		
		
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
	}
}